package com.education.realtime.util;

import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;


public class JDBCUtil {

    public static Connection getPhoenixConnection(String driver, String url) throws ClassNotFoundException, SQLException {
        return getJDBCConnection(driver,url,null,null);
    }

    public static Connection getJDBCConnection(String driver, String url,String user,String password) throws ClassNotFoundException, SQLException {
        Class.forName(driver);
        return DriverManager.getConnection(url,user,password);
    }

    public static <T> List<T> queryList(Connection conn,
                                        String querySql,
                                        Object[] args,
                                        Class<T> tClass) throws SQLException, IllegalAccessException, InstantiationException, InvocationTargetException {

        ArrayList<T> result = new ArrayList<>();
        System.out.println(querySql);
        PreparedStatement ps = conn.prepareStatement(querySql);

        //给占位符赋值
        for (int i = 0; args != null && i < args.length; i++) {

            ps.setObject(i + 1,args[i]);

        }

        //执行查询
        ResultSet resultSet = ps.executeQuery();
        //获取查询表的元数据信息
        ResultSetMetaData metaData = resultSet.getMetaData();
        //获取数据的行数
        int columnCount = metaData.getColumnCount();

        while (resultSet.next()){
            //创建一个T类型的对象，每行封装到一个对象中
            T t = tClass.newInstance();
            //每一行数据： 把这个一行数据的所有的列取出,封装到T类型的对象中
            for (int i = 1; i <= columnCount; i++) {
                String name = metaData.getColumnLabel(i);
                Object value = resultSet.getObject(i);

                //封装成T类型
                BeanUtils.setProperty(t,name,value);
            }
            result.add(t);
        }


        return result;
    }




}
